//
//  JDShopcartViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/4/2.
//

import UIKit
/// 购物车
class JDShopcartViewController: JDBaseViewController {

    fileprivate var myTableView: UITableView?
    fileprivate var bottomToolBarView: UIView?
    
    var submitButton: UIButton?
    var selectedNumLabel: UILabel?
    var submitPrice: UILabel?
    var removeButton: UIButton?
    
    var shopCartModels: [JDShopCartModel?]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupConfig()
        self.setupElements()
        self.setupBottomToolBarView()
        self.getNetData()
        // Do any additional setup after loading the view.
    }
    
    func setupConfig() {
        self.setupNavigationTitle("购物车")
        self.removeSeparatorLine()
//        self.customImageLeftBarButtonItem("xlbLogo", #selector(leftButtonAction), self)
        self.setupLeftBackItem()

        
        NotificationCenter.default.addObserver(self, selector: #selector(notificationRefresh), name: Notification.Name("notificationRefresh"), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(notificationRefresh), name: Notification.Name("refreshShopcart"), object: nil)
    }
    
    @objc func notificationRefresh() {
        self.getNetData()
    }

    @objc func leftButtonAction() {
        print("左上角的按钮")
    }
    
    func setupElements() {
        
        self.bottomToolBarView = UIView()
        self.view.addSubview(self.bottomToolBarView!)
        self.bottomToolBarView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.view)//.offset(-UIDevice().safeAreaInset.bottom)
            make.height.equalTo(104)
        })
        self.bottomToolBarView?.backgroundColor = .white
        
        self.myTableView = UITableView(frame: .zero, style: .grouped)
        self.view.addSubview(self.myTableView!)
        self.myTableView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(statusBarHeight+44)
            make.bottom.equalTo(self.bottomToolBarView!.snp.top)
        })
        self.myTableView?.delegate = self
        self.myTableView?.dataSource = self
        self.myTableView?.register(JDShopcartTableViewCell.self, forCellReuseIdentifier: "shopcartCell")
        self.myTableView?.separatorStyle = .none
        self.myTableView?.backgroundColor = color("#F5F6F8")
        
        self.myTableView?.addRefreshHeader { [weak self] in
            for subModels in (self?.shopCartModels ?? [JDShopCartModel?]()) {
                for model in subModels?.goodsList ?? [JDShopCartGoodsModel]() {
                    model.isSelected = false
                }
            }
            self?.selectedNumLabel?.text = "已选：0件"

            self?.submitPrice?.attributedText = String.init(format: "合计:￥%@", "0.00").attributed(firstStr: "合计:", first: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular),NSAttributedString.Key.foregroundColor: color("#333333")], secondStr: "￥", second: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .regular),NSAttributedString.Key.foregroundColor: color("#FA6161")], thirdStr: "0.00", third: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20, weight: .semibold),NSAttributedString.Key.foregroundColor: color("#FA6161")])
            
            self?.getNetData()
        }
    }
    
    func setupBottomToolBarView() {

        self.submitButton = UIButton(type: .custom)
        self.bottomToolBarView?.addSubview(self.submitButton!)
        self.submitButton?.snp.makeConstraints({ make in
            make.right.equalTo(self.bottomToolBarView!).offset(-12)
            make.width.equalTo(120)
            make.height.equalTo(48)
            make.centerY.equalTo(self.bottomToolBarView!).offset(-17)
        })
        self.submitButton?.setTitle("结算", for: .normal)
        self.submitButton?.setTitleColor(.white, for: .normal)
        self.submitButton?.backgroundColor = color("#FA6161")
        self.submitButton?.layer.cornerRadius = 24
        self.submitButton?.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        self.submitButton?.addTarget(self, action: #selector(submitAction), for: .touchUpInside)
        
        self.selectedNumLabel = UILabel()
        self.bottomToolBarView?.addSubview(self.selectedNumLabel!)
        self.selectedNumLabel?.snp.makeConstraints({ make in
            make.right.equalTo(self.submitButton!.snp.left).offset(-15)
            make.bottom.equalTo(self.submitButton!.snp.centerY)
            make.height.equalTo(18)
        })
        self.selectedNumLabel?.labelConfig(textAlignment: .right, font: UIFont.systemFont(ofSize: 13, weight: .regular), textColor: color("#9DA1B2"))
        self.selectedNumLabel?.text = "已选：0件"
        
        self.submitPrice = UILabel()
        self.bottomToolBarView?.addSubview(self.submitPrice!)
        self.submitPrice?.snp.makeConstraints({ make in
            make.right.equalTo(self.selectedNumLabel!)
            make.top.equalTo(self.submitButton!.snp.centerY)
            make.height.equalTo(28)
        })
        self.submitPrice?.labelConfig(textAlignment: .right, font: UIFont.systemFont(ofSize: 16, weight: .regular), textColor: color("#FA6161"), numberOfLines: 1)
        
        self.submitPrice?.attributedText = String.init(format: "合计:￥%@", "0.00").attributed(firstStr: "合计:", first: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular),NSAttributedString.Key.foregroundColor: color("#333333")], secondStr: "￥", second: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .regular),NSAttributedString.Key.foregroundColor: color("#FA6161")], thirdStr: "0.00", third: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20, weight: .semibold),NSAttributedString.Key.foregroundColor: color("#FA6161")])
        
        self.removeButton = UIButton(type: .custom)
        self.bottomToolBarView?.addSubview(self.removeButton!)
        self.removeButton?.snp.makeConstraints({ make in
            make.left.equalTo(self.bottomToolBarView!)
            make.top.equalTo(self.submitButton!)
            make.bottom.equalTo(self.submitButton!)
            make.width.equalTo(96)
        })
        self.removeButton?.setTitle("删除", for: .normal)
        self.removeButton?.setTitleColor(color("#333333"), for: .normal)
        self.removeButton?.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        self.removeButton?.addTarget(self, action: #selector(removeAction), for: .touchUpInside)
    }
    
    @objc func getNetData() {
        
        var params = [String: Any]()
        self.showLoading()
        JDNetWorkRequest(.getShopCartList(params)) { responseStr in
            self.dismissLoading()
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
                if let models = [JDShopCartModel].deserialize(from: responseStr, designatedPath: "data") {
                    self.shopCartModels = models
                }
            } else {
                self.view.toast(message: commonModel?.msg ?? "网络异常")
            }
            self.myTableView?.reloadData()
            
            printLog("购物车信息:\(responseStr)")
            self.myTableView?.mj_header?.endRefreshing()
            

            
        } failure: { error in
            self.dismissLoading()
            self.view.toast(message: error.localizedDescription)
        } error: { errorCode in
            self.dismissLoading()
            self.view.toast(message: "网络异常")
        }

    }
    
    @objc func submitAction() {
        
        var shopIds = [String]()
        
        for goodsModel in (self.shopCartModels ?? [JDShopCartModel?]())  {
            for speGoodsModel in goodsModel?.goodsList ?? [JDShopCartGoodsModel]() {
                if speGoodsModel.isSelected {
                    if let shopId = goodsModel?.shopId {
                        shopIds.append(shopId)
                    }
                }
            }
        }
        shopIds = Array(Set(shopIds))
        if shopIds.count > 1 {
            self.view.toast(message: "不可同时购买多家店铺的商品")
            return
        }
        
        var selectedInfoModel: JDShopCartModel?
        
        for goodsModel in (self.shopCartModels ?? [JDShopCartModel?]())  {
            for speGoodsModel in goodsModel?.goodsList ?? [JDShopCartGoodsModel]() {
                if speGoodsModel.isSelected {
                    selectedInfoModel = goodsModel
                    break
                }
            }
        }
        var selectedGoodsList = [[String: Any]]()
        
        for speGoodsModel in selectedInfoModel?.goodsList ?? [JDShopCartGoodsModel]() {
            
            if speGoodsModel.isSelected {
                var dic = [String: Any]()
                dic["goodsId"] = speGoodsModel.goodsId
                dic["goodsSkuId"] = speGoodsModel.goodsSkuId
                dic["goodsNum"] = speGoodsModel.count
                selectedGoodsList.append(dic)
            }
            
        }
        
        if selectedGoodsList.count <= 0 {
            self.view.toast(message: "请选择想要购买的商品")
            return;
        }
        
        self.showLoading()
        self.createPreOrder(selectedInfoModel) {[weak self] preOrderModel in
            self?.dismissLoading()
            if let preModel = preOrderModel {
                let confirmOrderVC = JDConfirmOrderViewController()
                confirmOrderVC.selectedShopCartModel = selectedInfoModel
                confirmOrderVC.preOrderModel = preModel
                self?.hidesBottomBarPushViewController(confirmOrderVC)
            }
        }
        
        
        
        
//        let confirmOrderVC = JDConfirmOrderViewController()
//        confirmOrderVC.selectedShopCartModel = selectedInfoModel
//        self.hidesBottomBarPushViewController(confirmOrderVC)
    }
    
    
    // 预订单接口
    func createPreOrder(_ selectedShopCartModel: JDShopCartModel?, completed: @escaping ((JDPreOrderModel?)->())) {
        var selectedGoodsList = [[String: Any]]()
                
        for speGoodsModel in selectedShopCartModel?.goodsList ?? [JDShopCartGoodsModel]() {
            
            if speGoodsModel.isSelected {
                var dic = [String: Any]()
                dic["goodsId"] = speGoodsModel.goodsId
                dic["goodsSkuId"] = speGoodsModel.goodsSkuId
                dic["goodsNum"] = speGoodsModel.count
                selectedGoodsList.append(dic)
            }
            
        }
        
        if selectedGoodsList.count <= 0 {
            return;
        }
        
        var params = [String: Any]()
        params["goodsList"] = selectedGoodsList
        JDNetWorkRequest(.preSaveOrder(params)) { responseStr in
            
            printLog("预订单接口:\(responseStr)")
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                if let model = JDPreOrderModel.deserialize(from: responseStr, designatedPath: "data") {
                    completed(model)
                } else {
                    JDTools.getKeyWindows()?.rootViewController?.view.toast(message: commonModel?.msg ?? "")
                    completed(nil)
                }
            } else {
                JDTools.getKeyWindows()?.rootViewController?.view.toast(message: commonModel?.msg ?? "")
                completed(nil)
            }
        } failure: { error in
            JDTools.getKeyWindows()?.rootViewController?.view.toast(message: error.errorDescription ?? "")
            completed(nil)
        } error: { errorCode in
            JDTools.getKeyWindows()?.rootViewController?.view.toast(message: String(format: "服务器异常:%d", errorCode))
            completed(nil)
        }
    }
    
    @objc func removeAction() {
        var alreadySelected = false
        for shopcartGoodsModels in self.shopCartModels ?? [JDShopCartModel?](){
            for goodsModel in shopcartGoodsModels?.goodsList ?? [JDShopCartGoodsModel]() {
                if goodsModel.isSelected {
                    alreadySelected = true
                }
            }
        }

        if alreadySelected == false {
            self.view.toast(message: "请选择想要删除的物品")
            return
        }
        
        let alertVC = UIAlertController(title: "删除", message: "确认删除此物品？", preferredStyle: .alert)
        
        let confirmAction = UIAlertAction(title: "确认", style: .default) {[weak self] alert in
            
            for shopcartGoodsModels in self?.shopCartModels ?? [JDShopCartModel?](){
                for goodsModel in shopcartGoodsModels?.goodsList ?? [JDShopCartGoodsModel]() {
                    printLog("商品id:\(goodsModel.goodsId)==>选中状态:\(goodsModel.isSelected)")
                    
                    if goodsModel.isSelected {
                        var params = [String: Any]()
                        params["goodsSkuId"] = goodsModel.goodsSkuId
                        self?.showLoading()
                        JDNetWorkRequest(.removeGoodsFromShopcart(params)) { responseStr in
                            
                            self?.dismissLoading()
                            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
                            if commonModel?.code == "0" {
                                
                                NSObject.cancelPreviousPerformRequests(withTarget: self)
                                self?.perform(#selector(self?.getNetData), with: nil, afterDelay: 1)
                                
                            }
                        } failure: { error in
                            self?.dismissLoading()
                            self?.view.toast(message: error.localizedDescription)
                            printLog("删除错误\(error)")
                        } error: { errorCode in
                            self?.dismissLoading()
                            self?.view.toast(message: "网络异常")
                            printLog("删除异常:\(errorCode)")
                        }
                    }
                    
                }
            }
            
            
        }
        
        let cancelAction = UIAlertAction(title: "取消", style: .cancel)
        
        alertVC.addAction(confirmAction)
        alertVC.addAction(cancelAction)
        
        self.present(alertVC, animated: true)
        
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    /// 切换选中商品
    func modifySelectedGoods() {
        var selectedNumer = 0
        var selectedTotalPrice = 0
        for subModel in self.shopCartModels ?? [JDShopCartModel]() {
            for goodsModel in subModel?.goodsList ?? [JDShopCartGoodsModel]() {
                if goodsModel.isSelected {
                    selectedNumer = selectedNumer + (goodsModel.count ?? 0)
                    selectedTotalPrice = selectedTotalPrice + (goodsModel.salePrice ?? 0)*(goodsModel.count ?? 0)
                }
            }
        }
        self.selectedNumLabel?.text = String.init(format: "已选：%zd件", selectedNumer)
        let priceStr = String.init(format: "%.2f", Double(selectedTotalPrice)/1000.0)
        
        self.submitPrice?.attributedText = String.init(format: "合计:￥%@", priceStr).attributed(firstStr: "合计:", first: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular),NSAttributedString.Key.foregroundColor: color("#333333")], secondStr: "￥", second: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .regular),NSAttributedString.Key.foregroundColor: color("#FA6161")], thirdStr: priceStr, third: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20, weight: .semibold),NSAttributedString.Key.foregroundColor: color("#FA6161")])
    }
}

extension JDShopcartViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.shopCartModels?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        let currentGoodsList = self.shopCartModels?[section]
        
        return currentGoodsList?.goodsList?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "shopcartCell") as? JDShopcartTableViewCell
        cell?.calculateCallBack = { [weak self] in
            self?.modifySelectedGoods()
        }
        if indexPath.row != self.shopCartModels?.count ?? 0 {
            cell?.containerView?.addCustomBottomLine(color("#F5F6F8"), with: 51, 12)
        }
        
        let currentModel = self.shopCartModels?[indexPath.section]?.goodsList?[indexPath.row]
        cell?.shopcartModel = currentModel
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 115
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 55
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let sectionHeaderView = UIView()
        sectionHeaderView.frame = CGRectMake(0, 0, screenWidth, 55)
        sectionHeaderView.backgroundColor = self.commonColor
        
        let sectionHeaderContainerView = UIView()
        sectionHeaderView.addSubview(sectionHeaderContainerView)
        sectionHeaderContainerView.snp.makeConstraints { make in
            make.left.equalTo(sectionHeaderView).offset(12)
            make.right.equalTo(sectionHeaderView).offset(-12)
            make.top.bottom.equalTo(sectionHeaderView)
        }
        sectionHeaderContainerView.backgroundColor = .white

        let storeInfoModel = self.shopCartModels?[section]
        
        let sectionHeaderBottomLine = UIView()
        sectionHeaderContainerView.addSubview(sectionHeaderBottomLine)
        sectionHeaderBottomLine.snp.makeConstraints { make in
            make.left.equalTo(sectionHeaderContainerView).offset(12)
            make.right.equalTo(sectionHeaderContainerView).offset(-12)
            make.bottom.equalTo(sectionHeaderContainerView)
            make.height.equalTo(1)
        }
        sectionHeaderBottomLine.backgroundColor = color("#F5F6F8")
        
        let storeName = UILabel()
        sectionHeaderContainerView.addSubview(storeName)
        storeName.snp.makeConstraints { make in
            make.left.equalTo(sectionHeaderContainerView).offset(12)
            make.top.equalTo(sectionHeaderContainerView)
            make.bottom.equalTo(sectionHeaderBottomLine.snp.top)
        }
        storeName.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .semibold), textColor: color("#333333"))
        storeName.text = storeInfoModel?.shopName//"三生有幸茶艺工艺"
        
        return sectionHeaderView
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
}
